package com.company;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import java.util.HashMap;

public class DBUtils {

    private static final String URL = "jdbc:mysql://182.92.6.166:3306/university?useSSL=false";  //  "jdbc:mysql://localhost:3306/XX"
    private static final String USER = "root";
    private static final String PASSWORD = "mysql123";
    private static Connection conn = null;
    public static Connection getConnection() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver"); //加载驱动
            System.out.println("驱动加载成功");
            conn = DriverManager.getConnection(URL,USER,PASSWORD);
            System.out.println("连接成功");
        } catch (SQLException ex) {
            System.out.println("连接失败");
            ex.printStackTrace();
        } catch (ClassNotFoundException ex) {
            System.out.println("驱动异常");
            ex.printStackTrace();
        }
        return conn;
    }
    public static HashMap<String, String> getUserInfoByName(String name) {
        HashMap<String, String> map = new HashMap<>();
        Connection conn = getConnection();
        System.out.println("连接成功");
        try {
            Statement st = conn.createStatement();
            String sql = "select * from user where name = '" + name + "'";
            ResultSet res = st.executeQuery(sql);
            if (res == null) {
                return null;
            } else {
                int cnt = res.getMetaData().getColumnCount();
                res.next();
                for (int i = 1; i <= cnt; ++i) {
                    String field = res.getMetaData().getColumnName(i);
                    map.put(field, res.getString(field));
                }
                conn.close();
                st.close();
                res.close();
                return map;
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("数据操作异常");
            return null;
        }
    }
    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HashMap<String,String> mp = DBUtils.getUserInfoByName("555");
                if(mp == null){
                    System.out.println("用户不存在");
                }else{
                    System.out.println("用户存在");
                }
            }
        }).start();
    }

}

